import 'package:flutter/material.dart';
import 'package:flutter_ahj_app/base/utils/oss/NetOSSUtils.dart';
import 'package:flutter_ahj_app/base/utils/oss/OSSUrlConsts.dart';
import 'package:flutter_ahj_app/base/utils/oss/OssUtil.dart';
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter_ahj_app/base/utils/oss/StsBean.dart';
import 'package:http_parser/http_parser.dart';

/*
 * 接口请求方法
 * 封装了传参方式及参数
 */
class ApiOssService {
  /*
  * 获取OSS Token
  */
  static Future<dynamic> getOssToken(BuildContext context,
      {cancelToken}) async {
    return NetOSSUtils.instance
        .post(context, OSSUrlConsts.URL_TOKEN, data: null, cancelToken: cancelToken);
  }

  static Future<dynamic> uploadImage (
      BuildContext context,StsBean stsBean, String uploadName, String filePath,
      {cancelToken}) async {
    BaseOptions options = new BaseOptions();
    options.responseType = ResponseType.plain; //必须,否则上传失败后aliyun返回的提示信息(非JSON格式)看不到
    //创建一个formdata，作为dio的参数
//    File file = new File(filePath);
    var image = await MultipartFile.fromFile(
      filePath,
      filename: OssUtil.instance.getImageNameByPath(filePath),
//        contentType: MediaType.parse(getcontentType(filePath))
    );
    FormData data = new FormData.fromMap({
      'Filename': uploadName,//文件名，随意
      'key': uploadName, //"可以填写文件夹名（对应于oss服务中的文件夹）/" + fileName
      'policy': OssUtil.policy,
      'OSSAccessKeyId':stsBean.data.accessKeyId,//Bucket 拥有者的AccessKeyId。
      'success_action_status': '200',//让服务端返回200，不然，默认会返回204
      'signature': OssUtil.instance.getSignature(stsBean.data.accessKeySecret),
      'x-oss-security-token':stsBean.data.securityToken,//临时用户授权时必须，需要携带后台返回的security-token
      'file': image//必须放在参数最后
    });
    return await NetOSSUtils.instance
        .post(context, OSSUrlConsts.URL_UPLOAD_IMAGE_OSS, data: data, options: options);
  }
}
String getcontentType(String FilenameExtension) {
  if (FilenameExtension.endsWith(".bmp")) {
    return "image/bmp";
  }
  if (FilenameExtension.endsWith(".gif")) {
    return "image/gif";
  }
  if (FilenameExtension.endsWith(".jpeg") ||
      FilenameExtension.endsWith(".jpg") ||
      FilenameExtension.endsWith(".png")) {
    return "image/jpg";
  }
  if (FilenameExtension.endsWith(".html")) {
    return "text/html";
  }
  if (FilenameExtension.endsWith(".txt")) {
    return "text/plain";
  }
  if (FilenameExtension.endsWith(".vsd")) {
    return "application/vnd.visio";
  }
  if (FilenameExtension.endsWith(".pptx") ||
      FilenameExtension.endsWith(".ppt")) {
    return "application/vnd.ms-powerpoint";
  }
  if (FilenameExtension.endsWith(".docx") ||
      FilenameExtension.endsWith(".doc")) {
    return "application/msword";
  }
  if (FilenameExtension.endsWith(".xml")) {
    return "text/xml";
  } if (FilenameExtension.endsWith(".mp4")) {
    return "video/mpeg4";
  }
  return "application/octet-stream";
}